<template>
	<div class="system-menu-container">
		<el-container >
            <el-aside width="320px" >
               <div>
                <el-tree :data="treeList" ref="orgtree" node-key="id" v-loading="loading"  :props="defaultProps" @node-click="handleNodeClick" :highlight-current="true" :default-expand-all="true">
                </el-tree>
               </div>
            </el-aside>
            <el-container height="100%">
                <el-main>
					<el-card>
						<el-row>
							<el-button  type="success" icon="ele-Edit" @click="addCOrg(ruleFormRef)">新增</el-button>
							<el-button   type="danger" icon="ele-Delete" @click="deleteCOrg(ruleFormRef)" >删除</el-button>
						</el-row>
						<el-form ref="ruleFormRef" :model="ruleForm" label-width="100px" :rules="rules" >
							<el-row>
								<el-col :span="23">
									<el-form-item label="机构名称" prop="orgName">
										<el-input v-model="ruleForm.orgName" :maxlength="50" ></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="机构简称" prop="shortName">
										<el-input v-model="ruleForm.shortName" :maxlength="50" ></el-input>
									</el-form-item>
								</el-col>
								<el-col :span="11">
									<el-form-item label="机构编码" prop="orgCode">
										<el-input v-model="ruleForm.orgCode" :maxlength="50"  placeholder="机构编码"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="23">
									<el-form-item label="上级机构" prop="parentOrgName">
										<el-input v-model="ruleForm.parentOrgName" :disabled="true" ></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="机构级别" prop="orgRank" >
										<el-select v-model="ruleForm.orgRank" placeholder="请选择机构级别" style="width:100%">
											<el-option v-for="(item,index) in dataDictionaryList['1030']" :key="index" :label="item" :value="index" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="11">
									<el-form-item label="机构分类" prop="orgType" >
										<el-select v-model="ruleForm.orgType" placeholder="请选择机构分类" style="width:100%">
											<el-option v-for="(item,index) in dataDictionaryList['1029']" :key="index" :label="item" :value="index" />
										</el-select>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row>
								<el-col :span="12">
									<el-form-item label="状态" prop="orgStatus" >
										<el-select v-model="ruleForm.orgStatus" placeholder="请选择状态" style="width:100%">
											<template v-for="(item,index) in dataDictionaryList['1001']">
												<el-option :key="index" :label="item" :value="index" v-if="'100103' != index"/>
											</template>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="11">
									<el-form-item label="排序" prop="ordernum">
										<el-input v-model.number="ruleForm.ordernum" type="number" min="0" max="99999999"></el-input>
									</el-form-item>
								</el-col>
							</el-row>
							<el-row style="text-align: right;margin-right:20px">
								<el-button :loading="loading" type="success" icon="ele-Check" @click="submitForm(ruleFormRef)">保存</el-button>
							</el-row>
						</el-form>
					</el-card>
					<el-card>
						<div class="taskDetails-content-title" style="margin-bottom: 10px">
                            岗位管理
                        </div>
						<div style="text-align:left">
							<el-button  type="success" icon="ele-Plus" @click="addHandle()">新增</el-button>
							<el-button  type="primary" icon="ele-Edit" @click="updateHandle()" :disabled="dataListSelections.length !== 1">修改</el-button>
							<el-button  type="primary" icon="ele-Edit" @click="setResEditHandle()" :disabled="dataListSelections.length !== 1">设置资源权限</el-button>
							<el-button  type="danger" icon="ele-Delete" @click="deleteResHandle()"  :disabled="dataListSelections.length <= 0">清除权限</el-button>
							<el-button  type="danger" icon="ele-Delete" @click="deleteHandle()"  :disabled="dataListSelections.length <= 0">删除</el-button>
						</div>
						<el-table :data="tableData" style="width: 100%" v-loading="dataListLoading"  ref="multipleTable" @selection-change="handleSelectionChange">
                            <el-table-column prop="id" type="selection" width="55"/>
                            <el-table-column prop="stationCode" label="岗位编码" />
                            <el-table-column prop="stationName" label="岗位名称" />
                            <el-table-column prop="shortName" label="简称" />
                            <el-table-column prop="status" label="状态" column-key="1001" :formatter="formatStatus" />
                            <el-table-column prop="stationRank" label="岗位类型" column-key="1031" :formatter="formatStatus"/>
                        </el-table>
						<el-pagination
							@size-change="onSelectSizeChange"
							@current-change="onSelectCurrentChange"
							:pager-count="5"
							:page-sizes="[10, 50, 200]"
							v-model:current-page="queryForm.page"
							background
							v-model:page-size="queryForm.limit"
							layout="total, sizes, prev, pager, next, jumper"
							:total="total" small>
						</el-pagination>
					</el-card>
				</el-main>
			</el-container>
		</el-container>
		<el-dialog :close-on-click-modal="false" :title="!stationForm.id ? '新增' : '修改'" ref="addOrUpdate" v-model="addOrUpdateVisible">
			<el-tabs v-model="activeName">
				<el-tab-pane label='岗位信息' name="first" :key="'first'">
					<el-form :model="stationForm" :rules="stationRule" ref="stationFormRef" @keyup.enter.native="stationFormSubmit(stationFormRef)" label-width="80px">
						<el-form-item label="所属机构" prop="orgName">
							<el-input v-model="stationForm.orgName" placeholder="所属机构" :disabled="true"></el-input>
						</el-form-item>
						<el-form-item label="岗位编码" prop="stationCode">
							<el-input v-model="stationForm.stationCode" placeholder="岗位编码" :maxlength="50"></el-input>
						</el-form-item>
						<el-form-item label="岗位名称" prop="stationName">
							<el-input v-model="stationForm.stationName" placeholder="岗位名称" :maxlength="50"></el-input>
						</el-form-item>
						<el-form-item label="岗位简称" prop="shortName">
							<el-input v-model="stationForm.shortName" placeholder="岗位简称" :maxlength="50"></el-input>
						</el-form-item>
						<el-form-item label="状态" prop="status">
							<el-select v-model="stationForm.status" placeholder="请选择状态" style="width:100%">
								<template v-for="(item,index) in dataDictionaryList['1001']">
									<el-option :key="index" :label="item" :value="index" v-if="'100103' != index"/>
								</template>
							</el-select>
						</el-form-item>
						<el-form-item label="岗位类型" prop="stationRank">
							<el-select v-model="stationForm.stationRank" placeholder="请选择岗位类型" style="width:100%">
								<el-option v-for="(item,index) in dataDictionaryList['1031']" :key="index" :label="item" :value="index" ></el-option>
							</el-select>
						</el-form-item>
					</el-form>
				</el-tab-pane>
				<el-tab-pane label="资源" name="second" :key="'second'">
					<el-tree :data="stationResTreeList" ref="stationRestree" node-key="id" :props="stationDefaultProps"  show-checkbox  :check-strictly="false"  :highlight-current="true">
					</el-tree>
				</el-tab-pane>
			</el-tabs>
			<template #footer>
				<span class="dialog-footer">
					<el-button  @click="addOrUpdateVisible = false">取消</el-button>
					<el-button  type="primary" @click="stationFormSubmit(stationFormRef)">确定</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog :close-on-click-modal="false" title="设置资源权限" ref="setResEdit" v-model="setResEditVisible">
			<el-tree :data="stationResTreeList" ref="stationRestree" node-key="id" :props="stationDefaultProps"  show-checkbox  :check-strictly="false"  :highlight-current="true">
			</el-tree>
			<template #footer>
				<span class="dialog-footer">
					<el-button  @click="setResEditVisible = false">取消</el-button>
					<el-button  type="primary" @click="setStationRes">确定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { ref, toRefs, reactive, onMounted, nextTick, defineComponent } from 'vue';
import { useRoute } from 'vue-router'
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
import {systemApi} from '/@/api/systemapi'
import { ElMessage, ElMessageBox, FormInstance, ElTree, ElLoading } from 'element-plus';
import { getCodeList } from '/@/utils/cacheDict'
export default defineComponent({
	setup() {
		const route = useRoute()
		const stores = useUserInfo()
		const { userInfos } = storeToRefs(stores)
		const state = reactive({
			loading: false,
			dataListLoading: false,
			tenantId: '',
			treeList: [],
			dataDictionaryList: {},
			dataListSelections: [],
			tableData: [],
			defaultProps: {
				children: "childList",
				label: "name"
			},
			ruleForm: {
				id: "",
				orgName: "",
				shortName: "",
				parentOrgName: "",
				ordernum: "",
				orgStatus: "",
				parentId: "",
				orgType: "",
				orgRank: "",
				orgCode: "",
				tenantId: ''
			},
			total: 0,
			totalSelect: 0,
			queryForm: {
				page: 1,
				limit: 10,
				dataForm: {
					orgId: "",
					orgName: "",
					stationId: "",
					stationName: ""
				}
			},
			rules: {
				orgName: [
				{
					required: true,
					message: "机构名称不能为空",
					trigger: "blur"
				}
				],
				orgStatus: [
				{
					required: true,
					message: "请选择状态",
					trigger: "change"
				}
				],
				ordernum: [
				{
					type: "number",
					message: "必须为数字值"
				}
				],
				orgType: [
				{
					required: true,
					message: "请选择机构分类",
					trigger: "change"
				}
				],
				orgRank: [
				{
					required: true,
					message: "请选择机构级别",
					trigger: "change"
				}
				],
				orgCode: [
				{
					required: true,
					message: "自定义编码不能为空",
					trigger: "blur"
				}
				],
				tenantId: [
					{
						required: true,
						message: "请选择租户",
						trigger: "blur"
					}
				]
			},
			stationForm: {
				id: "",
				orgId: "",
				orgName: "",
				stationCode: "",
				stationName: "",
				shortName: "",
				status: "",
				stationRank: "",
				tenantId: '',
				resId: []
			},
			addOrUpdateVisible: false,
			stationRule: {
				stationName: [
				{ required: true, message: "岗位名称不能为空", trigger: "blur" }
				],
				stationCode: [
					{ required: true, message: "岗位编号不能为空", trigger: "blur" }
				],
				status: [{ required: true, message: "状态不能为空", trigger: "blur" }]
				// stationRank: [{ required: true, message: "岗位类型", trigger: "blur" }]
			},
			activeName: "first",
			stationDefaultProps: {
				children: "childList",
				label: "name"
			},
			stationResTreeList: [],
			stationResours: [],
			setResEditVisible: false
		})

		const ruleFormRef = ref<FormInstance>()
		const orgtree = ref<InstanceType<typeof ElTree>>()
		const stationFormRef  = ref<FormInstance>()
		const stationRestree = ref<InstanceType<typeof ElTree>>()
		// 页面加载时
		onMounted(() => {
			//如果路由传过来就从路由获取租户id，否则直接从store获取当前用户的租户
			if(route.query.tenant){
				state.tenantId = route.query.tenant!.toString()
			} else {
				state.tenantId = userInfos.value.tenantId
			}
			// 数据字典
			getCodeList(state, ['1001', '1029', '1030', '1031'])
			getTreeList(state.tenantId)
		})

		const getTreeList = (tenantId: string) => {
			systemApi().getOrgsByTenantId(tenantId).then(data => {
				if (data) {
					state.treeList = data
				} else {
					state.treeList = []
				}
				state.loading = false;
			}).catch(() => {
				state.loading = false
			})
		}

		const handleNodeClick = (data: any) => {
			state.ruleForm.id = data.data.id
			state.ruleForm.orgName = data.data.orgName
			state.ruleForm.shortName = data.data.shortName
			state.ruleForm.orgStatus = data.data.orgStatus
			state.ruleForm.parentId = data.data.parentId
			state.ruleForm.ordernum = data.data.ordernum
			state.ruleForm.orgType = data.data.orgType
			state.ruleForm.orgRank = data.data.orgRank
			state.ruleForm.orgCode = data.data.orgCode
			state.ruleForm.tenantId = data.data.tenantId
			if (data.parentId !== "0") {
				state.ruleForm.parentOrgName = orgtree.value!.getNode(data.parentId).data.name
				// this.$refs.orgtree.getNode(data.parentId).data.label
			} else {
				state.ruleForm.parentOrgName = ""
			}
			state.queryForm.dataForm.orgId = data.data.id
			state.queryForm.dataForm.orgName = data.data.orgName
			queryStationList()
		}

		const addCOrg = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.resetFields()
			state.ruleForm.tenantId = state.tenantId
			state.ruleForm.id = ''
			if(orgtree.value!.getCurrentNode()){
				state.ruleForm.parentId = orgtree.value!.getCurrentNode().id
				state.ruleForm.parentOrgName = orgtree.value!.getCurrentNode().name
			}else{
				ElMessage.error('请选择上级机构')
			}
		}
		const deleteCOrg = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			if(orgtree.value!.getCurrentNode()){
				if (orgtree.value!.getCurrentNode().childList &&
				orgtree.value!.getCurrentNode().childList.length > 0
				){
					ElMessage.error('请先删除子级机构')
					return false
				}
				ElMessageBox.confirm('是否确定删除所选记录', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
				}).then(() => {
					systemApi().deleteOrgById(state.ruleForm.id).then(data => {
						if (data) {
							ElMessage.success("删除成功")
							formEl.resetFields()
							state.ruleForm.tenantId = state.tenantId
							state.ruleForm.id = ''
							getTreeList(state.tenantId)
						}else{
							ElMessage.error(data.msg)
						}
					}).catch(() => {
						ElMessage.error('删除失败')
					})
				})
			} else {
				ElMessage.error('请选择要删除的机构')
			}
		}
		const submitForm = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					// 提交数据
					if(!state.ruleForm.parentId){
						ElMessage.error('请选择上级机构')
						return false
					}
					ElMessageBox.confirm('是否确定提交', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
					}).then(() => {
						systemApi().saveOrg(state.ruleForm).then(data => {
							if (data) {
								ElMessage.success("保存成功")
								getTreeList(state.tenantId)
							}else{
								ElMessage.error(data.msg)
							}
						}).catch(() => {
							ElMessage.error('保存失败')
						})
					})
				}
			})
		}
		const queryStationList = () => {
			state.dataListLoading = true
			nextTick(() => {
				systemApi().queryStationList(state.queryForm).then(data => {
					if (data && data.code === 0) {
						state.tableData = data.page.list
						state.total = data.page.totalCount
					} else {
						state.tableData = []
						state.total = 0
					}
				}).finally(() => {
					state.dataListLoading = false
				})
			})
		}
		const addHandle = () => {
			if (!orgtree.value!.getCurrentNode()) {
				ElMessage.error('请选择机构')
				return
			}
			state.addOrUpdateVisible = true
			nextTick(() => {
				stationFormRef.value?.resetFields()
				state.stationForm.id = ''
				state.stationForm.orgId = state.queryForm.dataForm.orgId
				state.stationForm.orgName = state.queryForm.dataForm.orgName
				state.stationForm.tenantId = state.tenantId
				systemApi().getTenantStationResTree(state.stationForm.tenantId, '').then(data => {
					if (data) {
						state.stationResTreeList = data.tree;
						state.stationResours = data.asingRes;
						nextTick(() => {
							checkStation(data.asingRes);
						});
					} else {
						state.stationResTreeList = [];
					}
				})
			})
		}
		const checkStation = (asingRes: any) => {
			var checkArray = new Array();
			if (asingRes) {
				asingRes.forEach((item, index, arr) => {
				if (stationRestree.value!.getNode(item.menuId)) {
					if (stationRestree.value!.getNode(item.menuId).isLeaf) {
					// this.$refs.restree.setChecked(item.resourceId, true, false)
					checkArray.push(item.menuId);
					}
				}
				});
				// console.log(checkArray)
				stationRestree.value!.setCheckedKeys(checkArray, false);
			}
		} 
		const updateHandle = () => {
			if (!orgtree.value!.getCurrentNode()) {
				ElMessage.error('请选择机构')
				return
			}
			if (state.dataListSelections.length !== 1) {
				ElMessage.error('请选择一条岗位记录')
				return false;
			}
			state.addOrUpdateVisible = true
			nextTick(() => {
				stationFormRef.value?.resetFields()
				state.stationForm.id = state.dataListSelections[0].id
				state.stationForm.orgId = state.queryForm.dataForm.orgId
				state.stationForm.orgName = state.queryForm.dataForm.orgName
				state.stationForm.tenantId = state.tenantId
				state.stationForm.stationCode = state.dataListSelections[0].stationCode
				state.stationForm.stationName = state.dataListSelections[0].stationName
				state.stationForm.shortName = state.dataListSelections[0].shortName
				state.stationForm.status = state.dataListSelections[0].status
				state.stationForm.stationRank = state.dataListSelections[0].stationRank
				systemApi().getTenantStationResTree(state.stationForm.tenantId, state.stationForm.id).then(data => {
					if (data) {
						state.stationResTreeList = data.tree;
						state.stationResours = data.asingRes;
						nextTick(() => {
							checkStation(data.asingRes);
						});
					} else {
						state.stationResTreeList = [];
					}
				})
			})
		}
		const setResEditHandle = () => {
			if (state.dataListSelections.length !== 1) {
				ElMessage.error('请选择一条岗位记录')
				return false;
			}
			state.stationForm.id = state.dataListSelections[0].id
			state.stationForm.orgId = state.queryForm.dataForm.orgId
			state.stationForm.orgName = state.queryForm.dataForm.orgName
			state.stationForm.tenantId = state.tenantId
			state.setResEditVisible = true
			systemApi().getTenantStationResTree(state.stationForm.tenantId, state.stationForm.id).then(data => {
				if (data) {
					state.stationResTreeList = data.tree;
					state.stationResours = data.asingRes;
					nextTick(() => {
						checkStation(data.asingRes);
					});
				} else {
					state.stationResTreeList = [];
				}
			})
		}
		const deleteResHandle = () => {
			if (state.dataListSelections.length < 1) {
				ElMessage.error('请选择岗位记录')
				return false;
			}
			let ids = state.dataListSelections.map(item => {
				return item.id
			})
			ElMessageBox.confirm('是否确定删除所选记录的资源权限', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				let loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				systemApi().deleteStationRes(ids).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('处理成功')
						queryStationList()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error("处理失败！")
				}).finally(()=>{
					loading.close()
				})
			})
		}
		const deleteHandle = () => {
			if (state.dataListSelections.length < 1) {
				ElMessage.error('请选择岗位记录')
				return false;
			}
			let ids = state.dataListSelections.map(item => {
				return item.id
			})
			ElMessageBox.confirm('是否确定删除所选记录', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
			}).then(() => {
				let loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				})
				systemApi().deleteStation(ids).then(data => {
					if (data && data.code === 0) {
						ElMessage.success('处理成功')
						queryStationList()
					} else {
						ElMessage.error(data.msg)
					}
				}).catch(() => {
					ElMessage.error("处理失败！")
				}).finally(()=>{
					loading.close()
				})
			})
		}
		const handleSelectionChange = (val: any) => {
			state.dataListSelections = val
		}
		const onSelectSizeChange = (val: number) => {
			state.queryForm.limit = val;
			queryStationList()
		}
		const onSelectCurrentChange = (val: number) => {
			state.queryForm.page = val;
			queryStationList()
		}
		const formatStatus = (row, column, cellValue, index) => {
			if(Object.keys(state.dataDictionaryList).length>0) {
				if (cellValue) {
					return state.dataDictionaryList[column.columnKey][cellValue];
				}
			}
		}
		//岗位信息提交
		const stationFormSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return
			formEl.validate((valid: boolean) => {
				if (valid) {
					// 提交数据
					let checkResIds = stationRestree.value!.getCheckedKeys()
					checkResIds = checkResIds.concat(stationRestree.value!.getHalfCheckedKeys())
					state.stationForm.resId = checkResIds
					let loading = ElLoading.service({
						lock: true,
						text: '处理中',
						background: 'rgba(0, 0, 0, 0.7)',
					})
					systemApi().saveStation(state.stationForm).then(data => {
						if (data && data.code === 0) {
							state.addOrUpdateVisible = false
							queryStationList()
							ElMessage.success('保存成功')
						} else {
							ElMessage.error(data.msg)
						}
					}).catch(() => {
						ElMessage.error("保存失败！")
					}).finally(()=>{
						loading.close()
					})
				}
			})
		}
		const setStationRes = () => {
			let checkResIds = stationRestree.value!.getCheckedKeys()
			checkResIds = checkResIds.concat(stationRestree.value!.getHalfCheckedKeys())
			let loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			})
			systemApi().saveStationRes(state.stationForm.id, checkResIds).then(data => {
				if (data && data.code === 0) {
					state.setResEditVisible = false
					queryStationList()
					ElMessage.success('保存成功')
				} else {
					ElMessage.error(data.msg)
				}
			}).catch(() => {
				ElMessage.error("保存失败！")
			}).finally(()=>{
				loading.close()
			})
		}
		return {
			route,
			getTreeList,
			ruleFormRef,
			handleNodeClick,
			addCOrg,
			deleteCOrg,
			submitForm,
			orgtree,
			queryStationList,
			addHandle,
			updateHandle,
			setResEditHandle,
			deleteResHandle,
			deleteHandle,
			handleSelectionChange,
			onSelectSizeChange,
			onSelectCurrentChange,
			formatStatus,
			stationFormSubmit,
			stationFormRef,
			stationRestree,
			setStationRes,
			...toRefs(state),
		}
	}
})
</script>

<style scoped>
.el-main{
	--el-main-padding: 0px;
}
</style>